'use client';

import Link from 'next/link';
import Image from 'next/image';
import { WalletMultiButton } from '@solana/wallet-adapter-react-ui';
import { useConnection } from '@solana/wallet-adapter-react';
import { useEffect, useState } from 'react';
import { EnhancedWalletButton } from './EnhancedWalletButton';
import type { SupportedChain } from '@/contexts/MultiChainWalletContext';

export function PixelHeader() {
  const { connection } = useConnection();
  const [network, setNetwork] = useState<string>('');
  const [mounted, setMounted] = useState(false);
  const [selectedChain, setSelectedChain] = useState<SupportedChain | null>(null);
  const [showChainMenu, setShowChainMenu] = useState(false);

  // 颜色/风格映射
  const chainStyles: Record<SupportedChain, { btn: string; tag: string }> = {
    solana: { btn: 'from-purple-600 to-purple-500', tag: 'bg-purple-500/15 text-purple-500' },
    bsc: { btn: 'from-yellow-500 to-amber-500', tag: 'bg-amber-500/15 text-amber-600' },
    xlayer: { btn: 'from-blue-500 to-cyan-500', tag: 'bg-blue-500/15 text-blue-500' },
  };

  useEffect(() => { setMounted(true); }, []);

  useEffect(() => {
    const detect = async () => {
      try {
        const rpc = connection.rpcEndpoint;
        if (rpc.includes('localhost') || rpc.includes('127.0.0.1')) setNetwork('local');
        else if (rpc.includes('devnet')) setNetwork('Devnet');
        else if (rpc.includes('mainnet')) setNetwork('Mainnet');
        else setNetwork('unknow');
      } catch { setNetwork('unknow'); }
    };
    if (mounted) detect();
  }, [connection, mounted]);  return (
    <header className="pixel-nav">
      <div className="nav-inner">
        {/* Logo */}
        <Link href="/" className="flex items-center gap-2">
          <div className="p-2">
            <Image src="/logo_new.png" alt="C4" width={36} height={36} />
          </div>
          <span className="font-pixel text-base">c4pad.fun</span>
        </Link>

        {/* Links */}
        <nav className="nav-links">
          <Link href="/" className="nav-link">XLayer</Link>
          {/* <Link href="/xlayer" className="nav-link">XLayer</Link> */}
          <Link href="/bsc" className="nav-link">BSC</Link>

          <Link href="/sol" className="nav-link">SOLANA</Link>

          <Link href="/mint" className="nav-link">mint</Link>

          <Link href="/trading" className="nav-link">token trade</Link>

        </nav>

        {/* Right */}
        <div className="flex items-center gap-3">
          {/* Network */}
          <div className="text-xs text-gray-400 hidden md:block">{network}</div>

          {/* Chain Selector */}
          <div className="relative shrink-0">
            <button
              className={`px-2 py-1 rounded text-xs flex items-center gap-1 whitespace-nowrap bg-gray-800/70 border border-gray-600 hover:bg-gray-700 transition ${selectedChain ? '' : 'opacity-80'}`}
              onClick={() => setShowChainMenu(v => !v)}
            >
              {selectedChain ? (
                <span>
                  {selectedChain === 'solana' && '◎ Solana'}
                  {selectedChain === 'bsc' && '🔶 BSC'}
                  {selectedChain === 'xlayer' && '🔷 XLayer'}
                </span>
              ) : 'change chain'}
              <svg className="w-3 h-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9l6 6 6-6" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
            {showChainMenu && (
              <div className="absolute left-1/2 -translate-x-1/2 top-full mt-2 w-32 z-[9999] text-xs border border-gray-600 shadow-lg">
                {(['solana','bsc','xlayer'] as SupportedChain[]).map(c => (
                  <button
                    key={c}
                    className={`block w-full text-left px-3 py-2 pixel-button-secondary ${selectedChain===c?'bg-gray-700':''} first:rounded-t last:rounded-b hover:bg-gray-600`}
                    onClick={() => { setSelectedChain(c); setShowChainMenu(false); }}
                  >
                    {c==='solana' && '◎ Solana'}
                    {c==='bsc' && '🔶 BSC'}
                    {c==='xlayer' && '🔷 XLayer'}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Wallet Area (统一样式) */}
          {selectedChain ? (
            <div className="flex items-center gap-2">
              {/* 选中链标签 */}
              <span className={`hidden md:inline px-2 py-0.5 rounded text-[10px] font-medium ${chainStyles[selectedChain].tag}`}>
                {selectedChain === 'solana' && 'Solana'}
                {selectedChain === 'bsc' && 'BSC'}
                {selectedChain === 'xlayer' && 'X Layer'}
              </span>

              {/* 钱包连接按钮 - 统一使用 EnhancedWalletButton */}
              {selectedChain === 'solana' ? (
                <WalletMultiButton className={`!h-auto !py-1.5 !px-4 !text-xs !rounded !bg-gradient-to-r ${chainStyles['solana'].btn} !text-white !font-medium hover:brightness-110`} />
              ) : (
                <EnhancedWalletButton 
                  chain={selectedChain}
                  className={`bg-gradient-to-r ${chainStyles[selectedChain].btn} text-white`}
                />
              )}
            </div>
          ) : (
            <span className="text-[10px] text-gray-400">Please select a chain</span>
          )}
        </div>
      </div>
    </header>
  );
}
